//
//  PayMoneyViewController.m
//  WeiWeiHaircut
//
//  Created by 超群 on 15/10/15.
//  Copyright © 2015年 超群. All rights reserved.
//

#import "PayMoneyViewController.h"
#import "PayMoneyCell.h"
#import "PayMoneyInfoCell.h"
#import "QZMyOrderDetailVc.h"
#import "QZMyAppointDeatilVc.h"
#import "QZOrderModel.h"
#import "ShaoppingCarViewController.h"//购物车
#import "MyAppointmentViewController.h"//预约主页
#import "QZHairDetailViewController.h"//发型详情
#import "Order.h"
#import "DataSigner.h"
#import "AppointmentModel.h"
#import "QZMyAppointVc.h"
#import "QZMyAppointDeatilVc.h"
#import <AlipaySDK/AlipaySDK.h>

#define PID @"2088121188856374"
#define Email @"admin@vvgufen.com"

#import "WXApiRequestHandler.h"

@interface PayMoneyViewController () <UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>
{
    NSArray* titleArray;
    NSArray* infoArray;
    NSArray* imageArray;
    UIButton *selectButton;//选中的支付方式
    NSInteger _indexRow;
    NSString *_order_num;
    NSString *payMoneyNumber;
    
}
@end

@implementation PayMoneyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"支付";
    
    [self addBtnOnNavWithTitle:@"订单" andImageName:@"返回" andTarget:self andAction:@selector(backAction) andFrame:CGRectMake(0, 0, 45, 20) andDirection:left];
    [self buildTableViewUI];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(paySour) name:@"支付成功" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(paySour) name:@"微信支付成功" object:nil];
    
    titleArray = @[@"支付宝支付",
                   @"微信支付",
                   @"银行卡支付"];
    
    infoArray  = @[@"推荐有支付宝的账户使用",
                   @"推荐安装微信5.0以上版本的用户使用",
                   @"支持储蓄卡信用卡无需开通网银"];

    imageArray = @[[UIImage imageNamed:@"zhifubao.png"],
                   [UIImage imageNamed:@"weixin.png"],
                   [UIImage imageNamed:@"中国银联.png"]];
}
-(void)backAction
{
    UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"是否取消支付" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
    [view show];
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (_payAppointMoney || _payOrderMoney) {
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
 
    if (buttonIndex == 1) {
        if (_isAppointment) {
            
            QZMyAppointDeatilVc *appiontDetail = [[QZMyAppointDeatilVc alloc] init];
            appiontDetail.isPayView = YES;
            appiontDetail.model = self.appModel;
            [self.navigationController pushViewController:appiontDetail animated:YES];
            
        }else{
            QZMyOrderDetailVc *detailVc = [[QZMyOrderDetailVc alloc] init];
            detailVc.tmpOrder = self.model;
            detailVc.orderType = @"未付款";
            detailVc.isPayView = YES;
            [self.navigationController pushViewController:detailVc animated:YES];
        }

    }
    
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)buildTableViewUI
{
    self.tableView.delegate         = self;
    self.tableView.dataSource       = self;
    self.tableView.backgroundColor  = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:self.tableView];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([PayMoneyInfoCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([PayMoneyInfoCell class])];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([PayMoneyCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([PayMoneyCell class])];
}

#pragma mark - tableheaderView
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView* headerTitleView     = [[UIView alloc] initWithFrame:CGRectMake(20, 0, WIDTH, 40)];
    [headerTitleView setBackgroundColor:[UIColor whiteColor]];
    headerTitleView.backgroundColor     = [UIColor colorWithHexString:@"#eeeeee"];
    
    UILabel* headerTitleLabel   = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, WIDTH-50, 20)];
    [headerTitleLabel setTextColor:[UIColor blackColor]];
    headerTitleLabel.textAlignment      = NSTextAlignmentLeft;
    [headerTitleLabel setFont:[UIFont systemFontOfSize:16]];
    [headerTitleView addSubview:headerTitleLabel];
    
    if (section == 0) {
        headerTitleLabel.text           = @"订单详情";
    }else if(section == 1){
        headerTitleLabel.text           = @"支付方式";
    }
    return headerTitleView;
}

#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else
        return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 85;
    }else
        return 53;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
 
    PayMoneyCell* cell = [self.tableView cellForRowAtIndexPath:indexPath];
    selectButton.selected = NO;
    selectButton = cell.selectButton;
    selectButton.selected = YES;
    _indexRow = indexPath.row + 10;
    
    NSLog(@"indexPath.row = %ld",indexPath.row);
}

#pragma mark - tableView datasource
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        PayMoneyInfoCell * cell  = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([PayMoneyInfoCell class]) forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.userInteractionEnabled = NO;
        cell.prodNUmber.text = [NSString stringWithFormat:@"%ld件",self.model.amount?self.model.amount:1];
        
        
        if (_payAppointMoney) {
            cell.prodPrice.text = self.moneyServe;
        }else{
            
        cell.prodPrice.text = [NSString stringWithFormat:@"%@元",self.model.price?self.model.price:[[TMCache sharedCache] objectForKey:@"margin"]];
        }
        payMoneyNumber = [NSString stringWithFormat:@"%@",self.model.price?self.model.price:[[TMCache sharedCache] objectForKey:@"margin"]];
        return cell;
    }
    PayMoneyCell * cell  = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([PayMoneyCell class]) forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (indexPath.section == 1) {
        cell.titleLabel.text    = titleArray[indexPath.row];
        cell.infoLabel.text     = infoArray[indexPath.row];
        cell.titleImage.image   = imageArray[indexPath.row];
        
    }
    
    return cell;
}
#pragma mark- 支付按钮
- (IBAction)payMoneyTap:(UIButton *)sender {
    if (_indexRow == 11) {
        
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        NSString *url = [NSString stringWithFormat:@"%@%@",newPublicURL,@"Pay.Index"];
        [dic setObject:@"威威商城微信支付" forKey:@"title"];
        [dic setObject:payMoneyNumber forKey:@"price"];
        
        
        if (_isAppointment) {//预约
            
            if (_payAppointMoney) {//预约服务
                [dic setObject:[NSString stringWithFormat:@"%@VVLF",self.appModel.appoint_num] forKey:@"order_no"];
                [dic setObject:@"预约理发" forKey:@"body"];
                [dic setObject:@"http://vv.dc125.com/vv/Public/pay/wechat/WxHairOrderMoney.php" forKey:@"notify_url"];
            }else{//预约押金
                [dic setObject:self.appModel.appoint_num forKey:@"order_no"];
                [dic setObject:@"预约理发" forKey:@"body"];
                [dic setObject:@"http://vv.dc125.com/vv/Public/pay/wechat/WxHairOrderMoneyDeposit.php" forKey:@"notify_url"];
            }
            
        }else{ //商品
            [dic setObject:self.model.order_num forKey:@"order_no"];
            [dic setObject:self.model.order_title[0] forKey:@"body"];
            [dic setObject:@"http://vv.dc125.com/vv/Public/pay/wechat/WxProd.php" forKey:@"notify_url"];
            
        }

        [self.request QZRequest_POST:url parameters:dic tagNSString:@"微信支付" stopRequest:NO isSerializer:NO isCache:NO];
        return;
    }
    if (_indexRow == 10) {
        [self pay];
        return;
    }
    
    
    [[iToast makeText:@"请选择付款方式"] show];
    
    
}
-(void)pay{
    NSString *partner = PID;//合作ID
    NSString *seller = Email;// 支付宝账号
    NSString *privateKey= @"MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAN9wj0m1KYaOHPa07B3RnIu5RWWHb8L5MyKZsjAdMkohNXGOFaRbDSl/Rde4WHeZD2HqyXO6b11c/aqOpAscKN7Ncsjwx+1h+MckBvHPuBqY4eRL6E4C126c7paSeDJP4023tkKnTkS9iqP/gMuNRZLrFdnlwW4CTAQNyXdferk7AgMBAAECgYBiWnm4SDZvND8rmZgVyB7Qok0Z0/QuLuODZ4Q4CaIJX3TW92QvZKT2jz9/JXZLruRGhcMHXhmHT1eZrBApk8uo9NfcFEnwgUYTWrI1InWVH0Yrs45MKrsZxZFB4ku4EeY/CR3l8Siu5yvI7NHS0pTq2vmZdZDx3dLXd8YVYG36gQJBAPA5LBDcP5lXbsG+gAovl3fl3aS83Xx4QRoEA4aHD67xnwltPZmmxte0jowFcJEtBkRb/ADPQ1mVUWQ7j5SnR4UCQQDuHTUeDpCTwNMx0Qk6k4US0+N/CoBY3zV052J0v6HecFM/a/TgFs7UtAGjhQN7h78y9+AIEOlbSiyIoqkebPm/AkEAglnjqXp6IFErToJ6pAxTGsJm1P+PB/2RBfbrmtIrFnkSHWFjrb6r41ychSpmfMB7yBhJ1H6jQzcdJVCUhsuGqQJANcppVnnp1UcJLsbPM+lhdYhiay+fIPSDqf4fcspbsdlkJP6pWfotDUYA3MTOrZhT7BqtBIV1ggb2moNMezAZFwJAWM5Uuw+Tb4CL/csEfR63j1CHHlTT8mP9usnskUCbll56mufrim1PuJBP9MbC7cBZ1Y85qC7wsdgYryelBCCgLQ==";//私钥
    
    
    Order *myOrder = [[Order alloc] init];
    myOrder.partner = partner;
    myOrder.seller = seller;
    
    myOrder.tradeNO = self.model.order_num?self.model.order_num:self.appModel.appoint_num;//订单号
    myOrder.productName = self.model.order_title[0]?self.model.order_title[0]:@"预约服务";//订单标题
    myOrder.productDescription = self.model.order_title[0]?self.model.order_title[0]:@"预约服务";//订单描述，现在还没有
    
    
    
    if (_payAppointMoney) {//服务
        myOrder.amount = _moneyServe;
        myOrder.tradeNO = [NSString stringWithFormat:@"%@VVLF",self.appModel.appoint_num];
        myOrder.notifyURL = @"http://vv.dc125.com/vv/Public/pay/aliwap/HairOrderMoney.php";//预约 服务的费用
    }else{//押金 或者 商品
        myOrder.amount = self.model.price?self.model.price:[[TMCache sharedCache] objectForKey:@"margin"];
        myOrder.tradeNO = self.model.order_num?self.model.order_num:self.appModel.appoint_num;//订单号
        myOrder.notifyURL = _model?@"http://vv.dc125.com/vv/Public/pay/aliwap/notify.php":@"http://vv.dc125.com/vv/Public/pay/aliwap/HairOrderMoneyDeposit.php";//回调地址
    }
    
    
    
    NSLog(@"%@",myOrder.notifyURL);
    myOrder.service = @"mobile.securitypay.pay";
    myOrder.paymentType = @"1";
    myOrder.inputCharset = @"utf-8";
    myOrder.itBPay = @"30m";
    myOrder.showUrl = @"m.alipay.com";
    
    
    NSString *orderSpec = [myOrder description];
    
    NSLog(@"orderSpec = %@",orderSpec);
    
    id<DataSigner> signer = CreateRSADataSigner(privateKey);
    NSString *signedString = [signer signString:orderSpec];
    
    NSString *appScheme = @"weiweiHairCut";
    NSString *orderString = nil;
    
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            
            if ([resultDic[@"resultStatus"] integerValue] == 9000) {
                
                [[iToast makeText:@"支付成功"] show];
            }else{
                [[iToast makeText:@"支付失败"] show];
            }
            [self paySour];
        }];
    }
    

}

-(void)request_POST_FinishValue:(id)value tagNSString:(NSString *)tag{
    
    if ([tag isEqualToString:@"微信支付"]) {
        if ([value[@"data"][@"status"] integerValue] == 100) {
            NSDictionary *dic = value[@"data"][@"data"];
            if ([dic[@"prepayid"] class] == [NSNull class]) {
                [[iToast makeText:@"订单已支付"] show];
                return;
            }
            [self bizPay:dic];
        }else{
            [[iToast makeText:@"支付失败"] show];
            NSLog(@"%@",value);
        }
    }
    
}
- (void)bizPay:(NSDictionary *)dic {
    NSString *res = [WXApiRequestHandler jumpToBizPay:dic];
    if( ![@"" isEqual:res] ){
        UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"支付失败" message:res delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        
        [alter show];
    }
    
}


-(void)paySour{
    
    if (_payAppointMoney) {
        [self.navigationController popViewControllerAnimated:YES];
        
    }else{
        for (UIViewController *vCon in self.navigationController.childViewControllers) {
            //是从哪里来的 回到哪里去
            
            if ([vCon class] == [MyAppointmentViewController class] || [vCon class] == [ShaoppingCarViewController class] || [vCon class] == [QZHairDetailViewController class]||[QZMyAppointVc class] ) {
                
                [self.navigationController popToViewController:vCon animated:YES];
            }
        }
    }
}
@end
